package com.harmontronics.hanma.paas.paas.domain.app.repository.persistence;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.harmontronics.hanma.paas.paas.consts.DbConstants;
import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.Fields;
import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.PageTypeEnum;
import com.harmontronics.hanma.paas.paas.domain.app.repository.mapper.HmPageMapper;
import com.harmontronics.hanma.paas.paas.domain.app.repository.po.HmPagePO;
import org.springframework.stereotype.Repository;

import java.util.List;


/**
 * @author ldb
 */
@Repository("hmFlowableFormRepository")
public class HmPageRepository extends ServiceImpl<HmPageMapper, HmPagePO> {

    public IPage<HmPagePO> selectPage(QueryWrapper<HmPagePO> queryWrapper, Page<HmPagePO> page) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    public HmPagePO findByNameAndType(String name, PageTypeEnum typeEnum) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.NAME, name);
        queryWrapper.eq(Fields.TYPE_DB, typeEnum);
        return baseMapper.selectOne(queryWrapper);
    }

    public List<HmPagePO> findByModelId(Long modelId) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.MODEL_ID, modelId);
        return baseMapper.selectList(queryWrapper);
    }

    public List<HmPagePO> findByModelIdAndType(Long modelId, PageTypeEnum typeEnum) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.MODEL_ID, modelId);
        queryWrapper.eq(Fields.TYPE_DB, typeEnum);
        queryWrapper.orderByDesc(DbConstants.CREATE_DATE);
        return baseMapper.selectList(queryWrapper);
    }

    public int countByModelId(Long modelId) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.MODEL_ID, modelId);
        return baseMapper.selectCount(queryWrapper);
    }

    public boolean keyExists(String key) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.KEY_DB, key);
        queryWrapper.last("limit 1");
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    public HmPagePO findByKey(String key) {
        QueryWrapper<HmPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Fields.KEY_DB, key);
        queryWrapper.last("limit 1");
        return baseMapper.selectOne(queryWrapper);
    }


}